package cn.it.shop.wechat.dispatcher;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import cn.it.shop.model.flow.FlowParameter;
import cn.it.shop.model.flow.FlowReply;
import cn.it.shop.service.flow.FlowParameterService;
import cn.it.shop.service.flow.FlowReplyService;
import cn.it.shop.util.GlobalConstants;
import cn.it.shop.util.HttpUtils;
import cn.it.shop.util.MessageUtil;
import cn.it.shop.wechat.model.customermessage.ArticleCustomer;
import cn.it.shop.wechat.model.customermessage.News;
import cn.it.shop.wechat.model.customermessage.NewsCustomerMessage;
import cn.it.shop.wechat.response.Article;
import cn.it.shop.wechat.response.CustomerMessage;
import cn.it.shop.wechat.response.NewsMessage;
import cn.it.shop.wechat.response.TextMessage;
import net.sf.json.JSONObject;

/**
 * ClassName: MsgDispatcher
 * @Description: 消息业务处理分发器
 * @author fangyangsheng
 */
@Component("msgDispatcher")
//@Service("msgDispatcher")
public class MsgDispatcher{
	
	@Resource
	protected FlowReplyService flowReplyService;
	
	@Resource
	protected FlowParameterService flowParameterService;
	
	
	public  String processMessage(Map<String, String> map) {
		//不管哪种类型的消息回复的xml格式中都需要带有此两个节点
		String openid=map.get("FromUserName"); //用户 openid
        String mpid=map.get("ToUserName");   //公众号原始 ID
		
        //回复文本消息
        if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) { // 文本消息
        	Logger logger=Logger.getLogger(MsgDispatcher.class);
        	try{
	        	System.out.println("==============这是文本消息！");
	            //普通文本消息
	            TextMessage txtmsg=new TextMessage();
	            txtmsg.setToUserName(openid);
	            txtmsg.setFromUserName(mpid);
	            txtmsg.setCreateTime(new Date().getTime());
	            txtmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
	            
	            String content=map.get("Content");//取出用户发来的消息
	            if("1".equals(content)){
	                txtmsg.setContent("你好，你发送的内容是 1！");
	            }else if("2".equals(content)){
	                txtmsg.setContent("你好，你发送的内容是 2！");
	            }else if("3".equals(content)){
	            	//查询 id == 1的流程
	            	FlowReply flowReply = flowReplyService.get(1l);
	            	//获取该流程对应的图文
	            	FlowParameter flowParameter = flowReply.getFlowParameter();
	            	//推送该流程的图文
	            	flowParameterService.sendFlowMessage(flowParameter,flowReply.getId(),openid,0);
	                
	            }else if("4".equals(content)){
	            	//推送活动
	            	
	            	//跳转大转盘页面的url
	            	String link = "http://159sp15185.51mypc.cn/eaxmmvc/jump/activity/toTurntable.do";
	            	
	            	//请求参数
	        		HashMap<String, String> params = new HashMap<String, String>();
	        		params.put("openid", openid);//粉丝id
	        		//拼接url的方法
	        		String url = HttpUtils.buildUrl(link, params);
	        		
	        		NewsCustomerMessage newsCustomerMessage = new NewsCustomerMessage();
	            	newsCustomerMessage.setMsgtype("news");
	            	newsCustomerMessage.setTouser(openid);
	            	//设置图文集合实体,流程只需要一个图文
	            	List<ArticleCustomer> articles = new ArrayList<ArticleCustomer>();
	            	articles.add(new ArticleCustomer("大转盘活动","幸运大转盘",url,"http://www.dlbtn.com/dldtv/d/file/2014-07-11/ded2decea92f5fa8ac75d4b8df203496.jpg"));
	            	News news = new News();
	            	news.setArticles(articles);
	            	newsCustomerMessage.setNews(news);
	            	JSONObject jsonMessage = JSONObject.fromObject(newsCustomerMessage);
	            	//获取access_token
	            	//从全局变量工具类中取出access_token
	        		String accessToken = GlobalConstants.getInterfaceUrl("access_token");
	        		//从全局变量工具类中取出获取所有用户openid的url
	        		String sendMessage = GlobalConstants.getInterfaceUrl("sendMessage");
	        		sendMessage += accessToken;
	        		//发送
	        		String result = "";//存储结果
	        		try {
	        			 result = HttpUtils.sendPostBuffer(sendMessage,jsonMessage.toString());
	        		} catch (Exception e) {
	        			e.printStackTrace();
	        		}
	        		return result;
	                
	                
	            }else if("5".equals(content)){
	            	/**
	            	 * 转到智能客服
	            	 */
	            	CustomerMessage customer=new CustomerMessage();//创建智能客服
					customer.setToUserName(openid);//接收方帐号（收到的OpenID）
					customer.setFromUserName(mpid);//开发者微信号
					customer.setCreateTime(new Date().getTime());//消息创建时间 （整型）
					customer.setMsgType("transfer_customer_service");
					//出错了打印出格式化后的xml字符串,如果和文档对的上才是对的
					//System.out.println("请求智能客服"+MessageUtil.customerMessageToXml(customer));
					return MessageUtil.customerMessageToXml(customer);//转发到多客服
	            }else{
	            	txtmsg.setContent("你好，欢迎来关注MR方测试号！");
	            }
	            return MessageUtil.textMessageToXml(txtmsg);//执行java对象转为xml方法,把转后的xml返回
	            
        	}catch(Exception e){
        		logger.error(e,e);
        		System.out.println(e);
        	}
        }

        if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) { // 图片消息
            System.out.println("==============这是图片消息！");
            
            //对图文消息
            NewsMessage newmsg=new NewsMessage();
            //基础信息
            newmsg.setToUserName(openid);//用户 openid
            newmsg.setFromUserName(mpid);//公众号原始 ID
            newmsg.setCreateTime(new Date().getTime());
            newmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
            
            //图文消息体
            Article article=new Article();
            article.setDescription("这是图文消息 1"); //图文消息的描述
            article.setPicUrl("http://res.cuiyongzhi.com/2016/03/201603086749_6850.png"); //图文消息图片地址
            article.setTitle("图文消息 1");
            article.setUrl("http://www.baidu.com");//设置点击图片后跳转的链接
            
            List<Article> list=new ArrayList<Article>();
            list.add(article);     //这里发送的是单图文，如果需要发送多图文则在这里 list 中加入多个 Article 即可！
            newmsg.setArticleCount(list.size());
            newmsg.setArticles(list);
            return MessageUtil.newsMessageToXml(newmsg);//图文消息转为xml
            
            
        }

        if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) { // 链接消息
            System.out.println("==============这是链接消息！");
        }

        if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) { // 位置消息
            System.out.println("==============这是位置消息！");
            
            
        }

        if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)) { // 视频消息
            System.out.println("==============这是视频消息！");
        }

        if (map.get("MsgType").equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) { // 语音消息
            System.out.println("==============这是语音消息！");
        }

        return " ";
    }




	
	
	
	
	
}
